<template>
  <div>
    <!-- 加载进度条 -->
    <LoadingProgress
      :isLoading="isLoading"
      :progress="loadingProgress"
      :loadingText="loadingText"
      :backgroundImage="loadingBg"
    />

    <div class="background-overlay" style="background-color: rgb(5, 150, 105);">
      <Preview
        :PreviewMode="PreviewMode"
        :colors="colors"
        :downloadKey="downloadKey"
        :downloadVcard="downloadVcard"
        :featured="featured"
        :footerCredit=true
        :genInfo="genInfo"
        :hasLightBG="hasLightBG"
        :images="images"
        :primaryActions="primaryActions"
        :pubKeyIsValid="pubKeyIsValid"
        :secondaryActions="secondaryActions"
        :showAlert="showAlert"
        :username="username"
        class="rounded-b-2xl"
      />
    </div>
  </div>
</template>
<script>
import { mapActions, mapState } from 'vuex'
// import JSZip from 'jszip'
import { cardService } from '~/services/cardService'
import axios from 'axios'
import { uploadConfig } from '~/services/api.config'
import wx from 'weixin-js-sdk'

export default {
   ssr: false,
  components: {
    LoadingProgress: () => import('~/components/LoadingProgress.vue')
  },
  data() {
    return {
      downloadCheckList: [
        {
          label:
            'I did not attach any link or file that will cause any risk to the user',
          checked: false
        }
      ],
      images: {
        logo: {
          url: null,
          blob: null,
          ext: null,
          mime: null,
          resized: null
        },
        photo: {
          url: null,
          blob: null,
          ext: null,
          mime: null,
          resized: null
        },
        cover: {
          url: null,
          blob: null,
          ext: null,
          mime: null,
          resized: null
        },
        background: {
          url: null,
          blob: null,
          ext: null,
          mime: null,
          resized: null
        }
      },
      colors: {
        logoBg: {
          color: `#059669`,
          openPalette: false
        },
        mainBg: {
          color: `#ddd`,
          openPalette: false
        },
        buttonBg: {
          color: `#059669`,
          openPalette: false
        },
        cardBg: {
          color: `#fff`,
          openPalette: false
        }
      },
      genInfo: {
        fname: null,
        lname: null,
        pronouns: null,
        title: null,
        biz: null,
        addr: null,
        desc: null,
        key: null,
        tracker: null,
        fontLink: null,
        fontCss: null
      },
      primaryActions: [   {
        name: 'Mobile',
        icon: 'call',
        href: 'tel:',
        placeholder: '+XX XXXXX XXXXX',
        value: "12121",
        label: 'Mobile number',
        order: 1,
        isURL: 0
      },],
      filterPrimary: '',
      secondaryActions: [],
      filterSecondary: '',
      actions: {
        primaryActions: [
          {
            name: 'Mobile',
            icon: 'call',
            href: 'tel:',
            placeholder: '+XX XXXXX XXXXX',
            value: "12121",
            label: 'Mobile number',
            order: 1,
            isURL: 0
          },
          {
            name: 'Office',
            icon: 'call',
            href: 'tel:',
            placeholder: '+XX XXXXX XXXXX',
            value: null,
            label: 'Office number',
            order: 1,
            isURL: 0
          },
          {
            name: 'Home',
            icon: 'call',
            href: 'tel:',
            placeholder: '+XX XXXXX XXXXX',
            value: null,
            label: 'Home number',
            order: 2,
            isURL: 0
          },
          {
            name: 'SMS',
            icon: 'sms',
            href: 'sms:',
            placeholder: '+XX XXXXX XXXXX',
            value: null,
            label: 'SMS mobile number',
            order: 3,
            isURL: 0
          },
          {
            name: 'Email',
            icon: 'email',
            href: 'mailto:',
            placeholder: 'info@example.com',
            value: null,
            label: 'Email address',
            order: 4
          },
          {
            name: 'Website',
            icon: 'website',
            placeholder: 'https://example.com',
            value: null,
            label: 'Website URL',
            order: 5,
            isURL: 1
          },
          {
            name: 'Store',
            icon: 'store',
            placeholder: 'https://example.com/storeID',
            value: null,
            label: 'Online Store URL',
            order: 6,
            isURL: 1
          },
          {
            name: 'Location',
            icon: 'location',
            placeholder: 'https://osm.org/go/location',
            value: null,
            label: 'Map location URL',
            order: 7,
            isURL: 1
          },

          {
            name: 'Panorama',
            icon: 'panorama',
            placeholder: 'https://example.com/panorama',
            value: null,
            label: 'Panorama website link',
            order: 8,
            isURL: 1
          },
          {
            name: 'Telegram',
            icon: 'telegram',
            href: 'https://t.me/',
            placeholder: 'username',
            value: null,
            label: 'Telegram username',
            order: 9,
            isURL: 1
          },
          {
            name: 'Matrix',
            icon: 'matrix',
            href: 'https://matrix.to/#/',
            placeholder: '@username:matrix.org',
            value: null,
            label: 'Matrix userID',
            order: 10,
            isURL: 1
          },
          {
            name: 'WhatsApp',
            icon: 'whatsapp',
            placeholder: 'https://wa.me/profileID',
            value: null,
            label: 'WhatsApp profile URL',
            order: 11,
            isURL: 1
          },
          {
            name: 'Messenger',
            icon: 'messenger',
            href: 'https://m.me/',
            placeholder: 'username',
            value: null,
            label: 'Messenger username',
            order: 12,
            isURL: 1
          },
          {
            name: 'Skype',
            icon: 'skype',
            href: 'skype:',
            hrefEnd: '?chat',
            placeholder: 'username',
            value: null,
            label: 'Skype username',
            order: 13,
            isURL: 1
          },
          {
            name: 'Line',
            icon: 'line',
            href: 'https://line.me/ti/p/',
            placeholder: 'LINE ID',
            value: null,
            label: 'Line profile ID',
            order: 14,
            isURL: 1
          },
          {
            name: 'Viber',
            icon: 'viber',
            href: 'viber://chat?number=',
            placeholder: 'XX XXXXX XXXXX',
            value: null,
            label: 'Viber mobile number',
            order: 15,
            isURL: 1
          },
          {
            name: 'WeChat',
            icon: 'wechat',
            href: 'weixin://contact?username=',
            placeholder: 'WeChat ID',
            value: null,
            label: 'WeChat profile ID',
            order: 16,
            isURL: 1
          },
          {
            name: 'Calendar',
            icon: 'calendar',
            placeholder: 'https://example.com/calendarID',
            value: null,
            label: 'Calendar URL',
            order: 17,
            isURL: 1
          },
          {
            name: 'XMPP',
            icon: 'xmpp',
            href: 'xmpp:',
            placeholder: 'XMPP ID',
            value: null,
            label: 'XMPP ID',
            order: 18,
            isURL: 1
          }
          // {
          //   name: 'IRC',
          //   icon: 'irc',
          //   href: 'irc:',
          //   placeholder: 'IRC ID',
          //   value: null,
          //   label: 'IRC ID',
          //   order: 19,
          //   isURL: 1,
          // },
        ],
        secondaryActions: [
          // todo: Fix Instagram gradient icon preview
          {
            name: 'Instagram',
            icon: 'instagram',
            href: 'https://instagram.com/',
            placeholder: 'username',
            value: null,
            color: '#ffffff',
            light: 1,
            gradientIcon: 1,
            label: 'Instagram username'
          },
          {
            name: 'Threads',
            icon: 'threads',
            href: 'https://www.threads.net/',
            placeholder: '@username',
            value: null,
            color: '#000000',
            label: 'Threads username'
          },
          {
            name: 'Pixelfed',
            icon: 'pixelfed',
            placeholder: 'https://pixelfed.social/username',
            value: null,
            color: '#8d59a8',
            label: 'Pixelfed profile URL'
          },
          {
            name: 'Facebook',
            icon: 'facebook',
            href: 'https://facebook.com/',
            placeholder: 'username or pagename',
            value: null,
            color: '#1877f2',
            label: 'Facebook username or pagename'
          },
          {
            name: 'Diaspora',
            icon: 'diaspora',
            placeholder: 'https://diaspora.social/username',
            value: null,
            color: '#000000',
            label: 'Diaspora profile URL'
          },
          {
            name: 'Friendica',
            icon: 'friendica',
            placeholder: 'https://friendica.social/username',
            value: null,
            color: '#1d6e9a',
            label: 'Friendica profile URL'
          },
          {
            name: 'Twitter',
            icon: 'twitter',
            href: 'https://twitter.com/',
            placeholder: 'username',
            value: null,
            color: '#1da1f2',
            label: 'Twitter username'
          },
          {
            name: 'Mastodon',
            icon: 'mastodon',
            placeholder: 'https://mastodon.social/@username',
            value: null,
            color: '#2b90d9',
            label: 'Mastodon profile URL'
          },
          {
            name: 'LinkedIn',
            icon: 'linkedin',
            href: 'https://linkedin.com/',
            placeholder: 'in/username or company/companyname',
            value: null,
            color: '#0077b5',
            label: 'Linkedin username or companyname'
          },
          {
            name: 'YouTube',
            icon: 'youtube',
            href: 'https://youtube.com/',
            placeholder: 'channel name or ID',
            value: null,
            color: '#ff0000',
            label: 'Youtube channel name or ID'
          },
          {
            name: 'Vimeo',
            icon: 'vimeo',
            href: 'https://vimeo.com/',
            placeholder: 'channelname',
            value: null,
            color: '#1ab7ea',
            label: 'Vimeo channelname'
          },
          {
            name: 'Peertube',
            icon: 'peertube',
            placeholder: 'https://peertube.video/channelname',
            value: null,
            color: '#ffffff',
            light: 1,
            label: 'Peertube channel URL'
          },
          {
            name: 'Pinterest',
            icon: 'pinterest',
            href: 'https://pinterest.com/',
            placeholder: 'username',
            value: null,
            color: '#bd081c',
            label: 'Pinterest username'
          },
          {
            name: 'Behance',
            icon: 'behance',
            href: 'https://behance.net/',
            placeholder: 'username',
            value: null,
            color: '#1769ff',
            label: 'Behance username'
          },
          {
            name: 'Dribbble',
            icon: 'dribbble',
            href: 'https://dribbble.com/',
            placeholder: 'username',
            value: null,
            color: '#ea4c89',
            label: 'Dribbble username'
          },
          {
            name: 'Reddit',
            icon: 'reddit',
            href: 'https://reddit.com/',
            placeholder: 'username',
            value: null,
            color: '#ff5700',
            label: 'Reddit username'
          },
          {
            name: 'VK',
            icon: 'vk',
            href: 'https://vk.com/',
            placeholder: 'pagename',
            value: null,
            color: '#4a76a8',
            label: 'VK page URL'
          },
          {
            name: 'Snapchat',
            icon: 'snapchat',
            href: 'https://www.snapchat.com/add/',
            placeholder: 'username',
            value: null,
            color: '#fffc00',
            light: 1,
            label: 'Snapchat username'
          },
          {
            name: 'Tumblr',
            icon: 'tumblr',
            href: 'https://',
            hrefEnd: '.tumblr.com/',
            placeholder: 'username',
            value: null,
            color: '#2c4762',
            label: 'Tumblr blog URL'
          },
          {
            name: 'Quora',
            icon: 'quora',
            href: 'https://quora.com/',
            placeholder: 'username',
            value: null,
            color: '#a82400',
            label: 'Quora username'
          },
          {
            name: 'Medium',
            icon: 'medium',
            placeholder: 'https://medium.com/publication_name',
            value: null,
            color: '#000000',
            label: 'Medium publication'
          },
          {
            name: 'Discord',
            icon: 'discord',
            placeholder: 'https://discord.gg/invitecode',
            value: null,
            color: '#7289da',
            label: 'Discord channel invite link'
          },
          {
            name: 'Twitch',
            icon: 'twitch',
            href: 'https://twitch.tv/',
            placeholder: 'username',
            value: null,
            color: '#9146ff',
            label: 'Twitch username'
          },
          {
            name: 'Spotify',
            icon: 'spotify',
            href: 'https://open.spotify.com/user/',
            placeholder: 'username',
            value: null,
            color: '#1ed760',
            label: 'Spotify username'
          },
          {
            name: 'Soundcloud',
            icon: 'soundcloud',
            href: 'https://soundcloud.com/',
            placeholder: 'username',
            value: null,
            color: '#ff3300',
            label: 'Soundcloud username'
          },
          {
            name: 'Funkwhale',
            icon: 'funkwhale',
            placeholder: 'https://funkwhale.audio/username',
            value: null,
            color: '#ffffff',
            light: 1,
            label: 'Funkwhale username'
          },
          {
            name: 'GitHub',
            icon: 'github',
            href: 'https://github.com/',
            placeholder: 'username',
            value: null,
            color: '#333',
            label: 'Github username'
          },
          {
            name: 'GitLab',
            icon: 'gitlab',
            href: 'https://gitlab.com/',
            placeholder: 'username',
            value: null,
            color: '#171321 ',
            label: 'Gitlab username'
          },
          {
            name: 'Codeberg',
            icon: 'codeberg',
            href: 'https://codeberg.org/',
            placeholder: 'username',
            value: null,
            color: '#2185d0',
            label: 'Codeberg username'
          },
          {
            name: 'Yelp',
            icon: 'yelp',
            href: 'https://yelp.com/',
            placeholder: 'bizname',
            value: null,
            color: '#fff',
            light: 1,
            label: 'Yelp pagename'
          },
          {
            name: 'PayPal',
            icon: 'paypal',
            href: 'https://paypal.me/',
            placeholder: 'username',
            value: null,
            color: '#003087',
            label: 'PayPal.me URL'
          },
          {
            name: 'Patreon',
            icon: 'patreon',
            href: 'https://patreon.com/',
            placeholder: 'username',
            value: null,
            color: '#FF424D',
            label: 'Patreon URL'
          },
          {
            name: 'Open-Collective',
            icon: 'open-collective',
            href: 'https://opencollective.com/',
            placeholder: 'projectname',
            value: null,
            color: '#fff',
            light: 1,
            label: 'Open Collective projectname'
          },
          {
            name: 'TikTok',
            icon: 'tiktok',
            href: 'https://tiktok.com/',
            placeholder: 'username',
            value: null,
            color: '#fff',
            light: 1,
            label: 'TikTok username'
          },
          {
            name: 'Cash App',
            icon: 'cashapp',
            href: 'https://cash.app/',
            placeholder: '$username',
            value: null,
            color: '#fff',
            light: 1,
            label: 'Cash App username'
          },
          {
            name: 'Siilo',
            icon: 'siilo',
            href: 'https://app.siilo.com/qr/',
            placeholder: 'userID',
            value: null,
            color: '#17233b',
            label: 'Siilo userID'
          },
          {
            name: 'App Store',
            icon: 'appstore',
            placeholder: 'https://apps.apple.com/in/app/appname/id',
            value: null,
            color: 'linear-gradient(#5fc9f8, #147efb)',
            label: 'App Store developer/app URL'
          },
          {
            name: 'Play Store',
            icon: 'playstore',
            placeholder: 'https://play.google.com/store/apps/details?id=',
            value: null,
            color: '#fff',
            light: 1,
            label: 'Play Store developer/app URL'
          },
          {
            name: 'ArtStation',
            icon: 'artstation',
            href: 'https://www.artstation.com/',
            placeholder: 'username',
            value: null,
            color: '#171717',
            label: 'ArtStation username'
          },
          {
            name: 'Buy me a coffee',
            icon: 'buymeacoffee',
            href: 'https://www.buymeacoffee.com/',
            placeholder: 'username',
            value: null,
            color: '#ffdd00',
            light: 1,
            label: 'Buy me a coffee username'
          }
        ]
      },
      featured: [
        {
          title: 'Section title',
          content: []
        }
      ],
      hostedURL: null,
      footerCredit: true,
      PreviewMode: true,
      content: null,
      inView: false,
      showPreview: false,
      scrollPos: null,
      opening: false,
      isLoading: false,
      loadingProgress: 0,
      loadingText: '正在加载您的名片...'
    }
  },
  computed: {
    ...mapState(['theme']),
    loadingBg() {
      return this.images.background && this.images.background.url ? this.images.background.url : ''
    },
    getFullname() {
      let fn = this.genInfo.fname
      let ln = this.genInfo.lname
      return (fn + ln).length ? `${fn ? fn : ''}${ln ? ' ' + ln : ''}` : null
    },
    pubKeyIsValid() {
      if (this.genInfo.key) {
        if (!this.genInfo.key.match(/^(-----BEGIN PGP PUBLIC KEY BLOCK-----)/))
          return false

        if (!this.genInfo.key.match(/(-----END PGP PUBLIC KEY BLOCK-----)$/))
          return false

        return true
      } else return false
    },
    downloadChecked() {
      return this.downloadCheckList.filter((e) => e.checked).length == 3
    },
    username() {
      return this.getFullname
        ? this.getFullname.toLowerCase().replace(/\W+/g, '')
        : 'username'
    },
    orderedPrimaryActions() {
      return this.actions.primaryActions.sort((a, b) =>
        a.order > b.order ? 1 : a.order < b.order ? -1 : 0
      )
    },
    filteredPrimaryActions() {
      return this.orderedPrimaryActions.filter((e) =>
        e.name.toLowerCase().includes(this.filterPrimary.toLowerCase())
      )
    },
    orderedSecondaryActions() {
      return this.actions.secondaryActions.sort((a, b) =>
        a.name.localeCompare(b.name)
      )
    },
    filteredSecondaryActions() {
      return this.orderedSecondaryActions.filter((e) =>
        e.name.toLowerCase().includes(this.filterSecondary.toLowerCase())
      )
    },
    vCard() {
      const getNumber = (type) => {
        let no = this.primaryActions
          .map((e) => (e.name == type ? e.value : null))
          .filter((e) => e)[0]
        return no ? no.replace(/\s/g, '') : null
      }
      let email = this.primaryActions
        .map((e) => (e.name == 'Email' ? e.value : null))
        .filter((e) => e)[0]
      let website = this.primaryActions
        .map((e) => (e.name == 'Website' ? e.value : null))
        .filter((e) => e)[0]
      let actions = [
        ...this.primaryActions,
        ...this.secondaryActions.map((e) => {
          return { ...e, isURL: 1 }
        })
      ]
      let urls = actions
        .map((e) => {
          if (e.isURL && e.value) {
            return {
              title: e.name,
              url:
                (e.href ? e.href : '') + e.value + (e.hrefEnd ? e.hrefEnd : '')
            }
          }
          return false
        })
        .filter((e) => e)

      let note = this.genInfo.desc
        ? this.genInfo.desc.replace(/[\r\n]+/gm, '')
        : null
      let key = this.pubKeyIsValid ? window.btoa(this.genInfo.key) : null
      let randomNumber = Math.floor(100000000 + Math.random() * 900000)
      return {
        fn: this.genInfo.fname,
        ln: this.genInfo.lname,
        title: this.genInfo.title,
        org: this.genInfo.biz,
        addr: this.genInfo.addr,
        cell: getNumber('Mobile'),
        work: getNumber('Office'),
        home: getNumber('Home'),
        sms: getNumber('SMS'),
        email,
        hostedURL: this.hostedURL,
        website,
        urls,
        key,
        note,
        uid: `EnBizCard-${randomNumber}`
      }
    }
  },
  methods: {
    ...mapActions(['changeTheme']),
    togglePreview() {
      this.opening = true
      let c = this.$refs.container
      if (this.showPreview) {
        c.classList.remove('overflow-y-hidden', 'h-screen')
        window.scrollTo(0, this.scrollPos)
        this.opening = false
      } else {
        this.scrollPos = window.scrollY
        setTimeout(() => {
          c.classList.add('overflow-y-hidden', 'h-screen')
          this.opening = false
        }, 400)
      }
      this.showPreview = !this.showPreview
    },
    checkView() {
      let e = this.$refs.create
      if (e) {
        let top = e.getBoundingClientRect().top
        this.inView = this.showPreview ? true : top < 0
      }
    },
    async getValue() {
      if (this.$route.params.id) {
        this.isLoading = true
        this.loadingProgress = 0
        this.loadingText = '正在连接服务器...'

        try {
          // 模拟进度更新
          const progressInterval = setInterval(() => {
            if (this.loadingProgress < 80) {
              this.loadingProgress += Math.random() * 15
              if (this.loadingProgress > 30 && this.loadingText === '正在连接服务器...') {
                this.loadingText = '正在获取名片数据...'
              }
              if (this.loadingProgress > 60 && this.loadingText === '正在获取名片数据...') {
                this.loadingText = '正在处理数据...'
              }
            }
          }, 200)

          const res = await cardService.getCard(this.$route.params.id)
          clearInterval(progressInterval)

          this.loadingProgress = 90
          this.loadingText = '正在渲染界面...'

          const value = res.data.data.value
          if (value) {
            console.log('Received data:', value)

            // 分批更新数据以显示进度
            const keys = Object.keys(value)
            const batchSize = Math.max(1, Math.floor(keys.length / 5))

            for (let i = 0; i < keys.length; i += batchSize) {
              const batch = keys.slice(i, i + batchSize)
              batch.forEach(key => {
                if (this.$data.hasOwnProperty(key)) {
                  console.log(`Updating ${key}:`, value[key])
                  this.$set(this.$data, key, value[key])
                } else {
                  console.log(`Skipping unknown property: ${key}`)
                }
              })

              // 更新进度
              this.loadingProgress = 90 + (i / keys.length) * 8
              await new Promise(resolve => setTimeout(resolve, 50))
            }
          }

          this.loadingProgress = 100
          this.loadingText = '加载完成！'

          // 延迟隐藏加载界面，让用户看到完成状态
          setTimeout(() => {
            this.isLoading = false
          }, 500)

        } catch (error) {
          console.error('Failed to get card data:', error)
          this.loadingText = '加载失败，请重试'
          setTimeout(() => {
            this.isLoading = false
          }, 2000)
        }
      }
    },
    clearContent() {
      this.content = null
    },
    create() {
      this.$refs.create.scrollIntoView({ behavior: 'smooth' })
    },
    getTitle(e) {
      return e.toLowerCase().split(' ').join('_')
    },
    addFeature() {
      this.featured.push({
        title: 'Section title',
        content: []
      })
    },
    hasLightBG(e) {
      let hex = this.colors[e].color
      hex = hex.slice(1)
      if (hex.length === 3) {
        hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
      }
      let r = parseInt(hex.slice(0, 2), 16)
      let g = parseInt(hex.slice(2, 4), 16)
      let b = parseInt(hex.slice(4, 6), 16)
      const brightness = Math.round(
        (parseInt(r) * 299 + parseInt(g) * 587 + parseInt(b) * 114) / 1000
      )
      return brightness > 125 ? true : false
    },
    showAlert(content) {
      this.content = content
    },
    clearFilterActions() {
      this.filterPrimary = this.filterSecondary = ''
    },
    filteredAction(filterType, actionType) {
      if (this[filterType].length)
        this.addAction(actionType, this[filterType][0].name)
      this.clearFilterActions()
    },
    addAction(type, name) {
      let index = this.actions[type].findIndex((e) => e.name === name)
      this[type].push(this.actions[type][index])
      this.actions[type].splice(index, 1)
      this.clearFilterActions()
    },
    removeAction(type, index) {
      this.actions[type].unshift(this[type][index])
      this[type].splice(index, 1)
    },
    downloadVcard() {
      let blob = new Blob([this.$refs.vCard.$refs.vCard.innerText], {
        type: 'text/plain'
      })
      saveAs(window.URL.createObjectURL(blob), `${this.username}.vcf`)
    },
    downloadKey() {
      let blob = new Blob([this.genInfo.key], {
        type: 'text/plain'
      })
      saveAs(
        window.URL.createObjectURL(blob),
        `${this.getFullname}'s public key.asc`
      )
    },
    async resizeImage(type, mime, index1, index2) {
      let vm = this
      let reader = new FileReader()
      let file
      if (index2 >= 0) {
        if (type == 'image') {
          file = await this.featured[index1].content[index2].file
        } else if (type == 'music') {
          file = await this.featured[index1].content[index2].cover
        } else if (type == 'product') {
          file = await this.featured[index1].content[index2].image.file
        }
      } else {
        file = await this.images[type].blob
      }
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      let img = document.createElement('img')
      let maxWidth, maxHeight
      reader.onload = (e) => {
        img.src = e.target.result
        img.onload = () => {
          if (type == 'photo') {
            canvas.width = canvas.height = 320
          } else {
            if (type == 'logo') {
              maxWidth = 960
              maxHeight = 192
            } else {
              maxWidth = maxHeight = 960
            }
            let width = img.width
            let height = img.height

            if (width > maxWidth) {
              height *= maxWidth / width
              width = maxWidth
            }
            if (height > maxHeight) {
              width *= maxHeight / height
              height = maxHeight
            }
            canvas.width = width
            canvas.height = height
          }
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
          canvas.toBlob(
            async (blob) => {
              let image = new File([blob], type, {
                type: mime
              })

              try {
                // 创建 FormData 对象
                const formData = new FormData()
                formData.append('file', image)

                // 上传调整大小后的图片
                const response = await axios.post(
                  uploadConfig.uploadUrl,
                  formData,
                  {
                    headers: {
                      'Content-Type': 'multipart/form-data'
                    }
                  }
                )

                // 检查响应
                if (response.data && response.data.code === 0) {
                  const uploadedUrl = response.data.data.url

                  if (index2 >= 0) {
                    if (type == 'image') {
                      vm.featured[index1].content[index2].file = image
                      vm.featured[index1].content[index2].url = uploadedUrl
                    } else if (type == 'music') {
                      vm.featured[index1].content[index2].cover = image
                      vm.featured[index1].content[index2].coverUrl = uploadedUrl
                    } else if (type == 'product') {
                      vm.featured[index1].content[index2].image.file = image
                      vm.featured[index1].content[index2].image.url = uploadedUrl
                    }
                  } else {
                    vm.images[type].resized = image
                    vm.images[type].url = uploadedUrl
                  }
                } else {
                  console.error('Resize upload failed')
                }
              } catch (error) {
                console.error('Resize upload error:', error)
              }
            },
            mime,
            0.8
          )
        }
      }
      reader.readAsDataURL(file)
    },
    getWechatConfig(id) {
      let url = window.location.href.split('#')[0]
      cardService.getWxSign(url,id).then(res=>{
        if (res.data && res.data.data) {
          // let data ={
          //   "signature": "2c0fbf8c0e45d8d8fcee1b2a973586adb60d684f",
          //   "appId": "wxc289b815b2f4286d",
          //   "jsapi_ticket": "xN-5lpdNhLiE7IEBU_UcHnjhjax8-U5QuEYqprpzJjCTym1quidkPyk1IplVKk9icy9krmNxxhJSG1iSwZTSxg",
          //   "url": "http://localhost:3001/view/1/",
          //   "nonceStr": "bed49f27-d65b-4d4e-af34-48a240263ae4",
          //   "timestamp": "1750734527"
          // }
          let data = res.data.data;
          wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: data.appId, // 必填，公众号的唯一标识
            timestamp: data.timestamp, // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature,// 必填，签名
            jsApiList: [
              'updateAppMessageShareData',
              'updateTimelineShareData'
            ]  // 必填，需要使用的JS接口列表,
          })
          // 通过error接口处理失败验证
          // wx.error(function (errres) {
          //   console.info("失败：", errres);
          // });

          wx.ready(() => {
            // 获取手机号码
            const mobileAction = this.primaryActions.find(action => action.name === '手机号码' || action.name === '通话')
            const wechatAction = this.primaryActions.find(action => action.name === '公司电话')
            const mobileNumber = mobileAction ? mobileAction.value : ''
            const wechatName = wechatAction ? wechatAction.value : ''
            let desc = ''

            // 先添加店长信息
            if (this.genInfo.pronouns) {
              desc += this.genInfo.pronouns;
            }
            if (this.genInfo.title) {
              desc += '：' + this.genInfo.title;
            }

            // 再添加联系方式
            if (mobileNumber) {
              desc += desc ? `\n联系方式：${mobileNumber}` : `联系方式：${mobileNumber}`
            } else if (this.genInfo.biz) {
              desc += desc ? `\n${this.genInfo.biz}` : this.genInfo.biz
            }
            // if (wechatName) {
            //     if (desc) {
            //       desc += `\n公司电话：${wechatName}`
            //     }
            // }
            if (desc) {
              desc += "\nCreate By OE电子名片"
            }
            let shareInfo = {
              title: this.genInfo.fname + this.genInfo.lname + '的名片',
              desc: desc,
              link: url,
              imgUrl: this.images.photo.url || this.images.cover.url || '' // 优先使用个人照片，如果没有则使用封面照片
            }

            // wx.onMenuShareTimeLine(shareInfo)
            wx.onMenuShareAppMessage(shareInfo)
            wx.onMenuShareQQ(shareInfo)
            wx.onMenuShareWeibo(shareInfo)
            wx.onMenuShareQZone(shareInfo)

            wx.updateAppMessageShareData(shareInfo)
            wx.updateTimelineShareData(shareInfo)

            console.log('微信配置已就绪')
          })
        } else {
          console.error('Invalid response from getWxSign:', res)
        }
      }).catch(err => {
        console.error('Error fetching WeChat config:', err)
      })

    },
    getTrackingCode() {
      let regex = /<script[^<]*<\/script>/g
      let tracker = this.genInfo.tracker
      if (regex.test(tracker)) {
        let scripts = tracker.match(regex)
        let temp = document.createElement('div')
        temp.innerHTML = tracker
        return scripts.length && temp
      }
      return false
    }
  },
  mounted() {
    window.addEventListener('scroll', this.checkView)
    // window.onbeforeunload = function () {
    //   return 'Your work will be lost.'
    // }
    if (this.$route.params.id) {
      this.getValue()
    }

    const qrScript = document.createElement('script')
    qrScript.innerText =
      'let m=document.getElementById("modal"),c=document.getElementById("close"),ki=document.getElementById("keyView"),cv=document.getElementById("copyView"),curl=document.getElementById("copyURL"),qrv=document.getElementById("qrView"),qr=document.getElementById("qr"),s=document.getElementById("share"),sqr=document.getElementById("showQR"),sk=document.getElementById("showKey");function tC(e){"2rem"==e.style.top?(e.style.visibility="visible",e.style.top="0px",e.style.opacity=1):(e.style.top="2rem",e.style.opacity=0,setTimeout(()=>{e.style.visibility="hidden"},200))}function dN(e){e.style.display="none"}window.addEventListener("load",()=>{document.querySelector("#topActions").style.display="flex",qr.innerHTML=new QRCode({content:window.location.href,container:"svg-viewbox",join:!0,ecl:"L",padding:0}).svg()}),navigator.canShare?s.addEventListener("click",()=>{navigator.share({title:document.title,text:"You can view my Digital Business Card here:",url:window.location.href})}):s.addEventListener("click",()=>{tC(m),cv.style.display="flex",dN(qrv),ki&&dN(ki)}),sqr.addEventListener("click",()=>{tC(m),qrv.style.display="block",dN(cv),ki&&dN(ki)}),sk&&sk.addEventListener("click",()=>{tC(m),ki&&(ki.style.display="flex"),dN(cv),dN(qrv)}),c.addEventListener("click",()=>tC(m)),curl.addEventListener("click",async()=>{let e=curl.querySelectorAll(".iconColor")[1];await navigator.clipboard.writeText(window.location.href).then(t=>{e.innerText="Copied",setTimeout(()=>{e.innerText="Copy URL"},1e3)})});'
    document.body.appendChild(qrScript)

    this.getWechatConfig(this.$route.params.id)
  },
  validate({ params }) {
    // 允许访问 /edit/ 和 /edit/new 和 /edit/:id
    return true
  },
}
</script>

<style scoped>
.background-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1; /* 确保背景在最底层 */
}
</style>
